import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { Observable, throwError } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { LogService } from "src/views/log/log.service";
import { Request, Response } from 'express';

/**
 * 日志拦截器 - 记录请求和响应信息
 */
@Injectable()
export class LoggerInterceptor implements NestInterceptor {
  constructor(private logService: LogService) { }

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const response = context.switchToHttp().getResponse<Response>();
    const startTime = Date.now();

    // 记录请求开始
    console.log(`[${new Date().toISOString()}] ${request.method} ${request.originalUrl} - 开始处理请求`);

    return next.handle().pipe(
      tap((data) => {
        // 记录成功响应
        const responseTime = Date.now() - startTime;
        this.logService.logRequest(request, data, responseTime);
        
        console.log(`[${new Date().toISOString()}] ${request.method} ${request.originalUrl} - 响应成功 (${responseTime}ms)`);
      }),
      catchError((error) => {
        // 记录错误响应
        const responseTime = Date.now() - startTime;
        this.logService.logRequest(request, null, responseTime, error);
        
        console.error(`[${new Date().toISOString()}] ${request.method} ${request.originalUrl} - 响应错误 (${responseTime}ms):`, error.message);
        
        return throwError(() => error);
      })
    );
  }
} 